//
//  GHPhotoBrowserCell.swift
//  Browser
//
//  Created by 刘光华 on 16/4/28.
//  Copyright © 2016年 liuguanghua. All rights reserved.
//

import UIKit
import Masonry
import SDWebImage

class GHPhotoBrowserCell: UICollectionViewCell {
    
    // MARK:- 懒加载
    lazy var imageView: UIImageView = {
        
        let imageView = UIImageView()
        
        self.contentView.addSubview(imageView)
        
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        
        imageView.clipsToBounds = true
        
        return imageView
        
    }()
    
    var shop : GHShop? {
        
        didSet {
            
            // nil值校验
            guard let smallImageUrl = shop?.q_pic_url else {
                return
            }
            
            // 获取小图片
            var smallImage = SDImageCache.sharedImageCache().imageFromMemoryCacheForKey(smallImageUrl)
            
            if smallImage == nil {
                smallImage = UIImage(named: "empty_picture")
            }
            
            // 根据小图片的宽高比计算出imageView的高度,并设置约束
            setImageViewConstraintsWithImage(smallImage)
            
            // 校验大图片
            guard let bigImageUrlString = shop?.z_pic_url else {
                return
            }
            let bigImageUrl = NSURL(string: bigImageUrlString)
            // 设置图片
            imageView.sd_setImageWithURL(bigImageUrl, placeholderImage: UIImage(named: "empty_picture")) { (image: UIImage!, error: NSError!, type: SDImageCacheType, url: NSURL!) -> Void in
                
                // 为什么这里打印会崩
//                print(error)
                self.setImageViewConstraintsWithImage(image)
                
            }
            
        }
        
    }
}



// MARK:- 自定义方法
extension GHPhotoBrowserCell {
    
    /// 根据图片设置imageView的约束
    func setImageViewConstraintsWithImage(image: UIImage) {
        
        let imageViewFrame = calculateImageViewHeight(image)
        
        // 设置约束
        // 由于cell要循环利用,所以经常设置imageView的约束,使用remakeConstraints
        imageView.gh_remakeConstraintsWithFrame(imageViewFrame)

        layoutIfNeeded()
        
    }
    
    
}

